package com.itqf.controller;

import com.itqf.entity.TbItem;
import com.itqf.service.TbItemService;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @Description:
 * @Company: 千锋互联
 * @Author: 李丽婷
 * @Date: 2021/1/19
 * @Time: 上午11:06
 */
@WebServlet("/find")
//两个工厂  1）spring:  mapper  service
//         2)servlet web容器构建的对象
public class TbItemServlet extends HttpServlet {

    //依赖service
    //private TbItemService tbItemService = new TbItemServiceImpl();//1）强耦合  2）mapper无法注入
    private TbItemService tbItemService;


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       //构建工厂 xml解析  反射构建对象
        //如果servlet数量比较多，那么需要频繁的构建工厂（频繁io操作，性能差...）
//        ApplicationContext ac = new ClassPathXmlApplicationContext("spring-tx.xml");
//        tbItemService = (TbItemService) ac.getBean("tbItemServiceImpl");


        //构建一个spring工厂即可。？？how？
        WebApplicationContext wac = WebApplicationContextUtils.
                getWebApplicationContext(req.getServletContext());

        tbItemService = (TbItemService) wac.getBean("tbItemServiceImpl");


        List<TbItem> list = tbItemService.findAll();

        req.setAttribute("tbItems",list);

        req.getRequestDispatcher("/show.jsp").forward(req,resp);

    }
}
